package com.quanyue.haircut.shop.service.impl;

import com.quanyue.auto.util.AssertUtils;
import com.quanyue.haircut.domain.entity.IntegralConvert;
import com.quanyue.haircut.domain.entity.UserIntegral;
import com.quanyue.haircut.shop.dto.IntegralOrderDetail;
import com.quanyue.haircut.shop.mapper.IntegralConvertMapper;
import com.quanyue.haircut.shop.mapper.IntegralMapper;
import com.quanyue.haircut.shop.service.IntegralService;
import com.vhuomai.mybatis.mapper.page.Page;
import com.vhuomai.mybatis.mapper.page.PageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;
import java.time.LocalDateTime;

@Service
public class IntegralServiceImpl implements IntegralService {
    @Autowired
    private IntegralMapper integralMapper;
    @Autowired
    private IntegralConvertMapper convertMapper;

    @Override
    public UserIntegral updateIntegral(Integer userId, Integer shopId, BigInteger integer) {
        UserIntegral check = this.findIntegral(userId, shopId);
        if (check != null) {
            check.setIntegral(integer);
            check.setModifyTime(LocalDateTime.now());
            integralMapper.updateSelective(check);
        } else {
            check = new UserIntegral();
            check.setIntegral(integer);
            check.setUserId(userId);
            check.setShopId(shopId);
            check.setCreateTime(LocalDateTime.now());
            check.setModifyTime(LocalDateTime.now());
            integralMapper.insert(check);
        }
        return check;
    }

    @Override
    public UserIntegral findIntegral(Integer userId, Integer shopId) {
        return integralMapper.findByUserAndShop(userId, shopId);
    }

    @Override
    public Page <IntegralOrderDetail> findIntegralOrder(Integer shopId, PageRequest request) {
        request.setAsc(false);
        request.setOrderBy("c.create_time");
        return integralMapper.findByOrderDetail(shopId, request);
    }

    @Override
    @Transactional
    public void integralProductRecord(IntegralConvert integralConvert) {
        UserIntegral integral1 = this.findIntegral(integralConvert.getUserId(), integralConvert.getShopId());
        BigInteger userIntegral = BigInteger.ZERO;
        if (integral1 != null) userIntegral = integral1.getIntegral();
        if (userIntegral.compareTo(BigInteger.valueOf(integralConvert.getIntegralCount())) < 0) {
            throw new AssertUtils.ValidateException("用户积分不够");
        }
        integralConvert.setCreateTime(LocalDateTime.now());
        convertMapper.insert(integralConvert);
        BigInteger integral = userIntegral.subtract(BigInteger.valueOf(integralConvert.getIntegralCount()));
        this.updateIntegral(integralConvert.getUserId(), integralConvert.getShopId(), integral);
    }
}
